<template>
  <el-dialog
    :title="plugin.lang('voucher.button')"
    v-model="show"
    :width="500"
  >
    <el-alert :title="plugin.lang('voucher.code') + ': ' + form.code" type="warning" :closable="false" />
    <el-form ref="formRef" :model="form" :rules="rules" label-position="top" style="margin-top: 20px">
      <el-form-item :label="plugin.lang('voucher.status_money')" prop="status_money">
        <div style="width: 100%; overflow: hidden; text-align:left">
          <el-input-number 
            ref="input"
            v-model="form.status_money" 
            @focus="(e) => e.target.select()" 
            @keyup.enter="onPost"
            :min="0.01" 
            :max="Number(form.money)" 
            :precision="2" 
            style="width: 100%" 
            controls-position="right" 
          />
        </div>
      </el-form-item>
      <el-form-item :label="plugin.lang('voucher.log.remarks')">
        <el-input v-model="form.remarks" @keyup.enter="onPost"></el-input>
      </el-form-item>
    </el-form>
    <el-button type="warning" style="width: 100%" :loading="loading" @click="onPost">{{ plugin.lang('voucher.button') }}</el-button>
  </el-dialog>
</template>
<script>
import { ref, nextTick } from 'vue'
import app from '@/app'
import voucherModel from '../../model/voucher'

export default {
  setup() {
    // 插件
    const plugin = app.plugin.index

    // 对话框
    const show = ref(false)

    // 表单
    const formRef = ref(null)
    const form = ref({})

    // 输入框
    const input = ref(null)

    // 验证
    const rules = {
      status_money: [
        { required: true, message: ' ', trigger: 'blur' }
      ]
    }

    // 打开
    const open = async(data) => {
      form.value = Object.assign({}, data)

      // 核销金额
      form.value.status_money = Number(data.money)

      show.value = true

      // 焦点
      await nextTick()
      input.value.focus()
    }

    // 更新
    const loading = ref(false)
    const onPost = () => {
      formRef.value.validate(valid => {
        if (valid) {
          loading.value = true
          voucherModel.status(form.value).then(() => {
            // 更新列表
            show.value = false
          }).finally(() => {
            loading.value = false
          }).catch(res => {
            plugin.message('warning', 'voucher.' + res.message)
          })
        }
      })
    }

    return {
      lang: app.lang,
      plugin,
      show,
      open,
      voucherModel,
      formRef,
      form,
      input,
      rules,
      loading,
      onPost, 
    }
  }
}
</script>